package org.camunda.bpm.getstarted.loanapproval.controller;

import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.ProcessEngineService;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.impl.form.validator.FormFieldValidationException;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.rest.dto.VariableValueDto;
import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.exception.RestException;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.getstarted.loanapproval.mapper.TicketMapper;
import org.camunda.bpm.getstarted.loanapproval.mapper.TicketTaskMapper;
import org.camunda.bpm.getstarted.loanapproval.pojo.dto.CompleteParams;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.TicketDO;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.TicketTaskDO;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.WorkstationGroupDO;
import org.camunda.bpm.getstarted.loanapproval.pojo.entity.WorkstationTaskDO;
import org.camunda.bpm.model.bpmn.Bpmn;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.core.Response;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("ticket")
public class TicketController {
    @Autowired
    private TicketMapper ticketMapper;

    private ProcessEngine engine;

    @Autowired
    private TicketTaskMapper ticketTaskMapper;

    public TicketController(){
        engine = ProcessEngines.getDefaultProcessEngine();
    }

    // 取号开始任务
    @GetMapping("generateTicket")
    @ResponseBody
    public void generateTicket(){
        TestAop testAop = new TestAop();
        testAop.generateTicket();
//      http://localhost:8080/api/engine/engine/default/task?assignee=demo&processInstanceId=a8c130ec-ec30-11ea-8807-704d7b86b42c&maxResults=15
        FormService formService = this.engine.getFormService();
        RuntimeService runtimeService = this.engine.getRuntimeService();
        TicketDO ticketDO = new TicketDO();
        ticketDO.setTicketNo(ticketMapper.selectGenerateNo());
        ticketDO.setCreateTime(new Date());
        ticketDO.setUpdateTime(new Date());
        ticketDO.setTicketDisplayNo("A" + ticketDO.getTicketNo());
        ticketMapper.insert(ticketDO);
        // 定义参数
        Map<String,Object> variables = new HashMap<>();
        variables.put("ticketId", ticketDO.getId());
        // 定义
        // 获取流程最新版本
        ProcessDefinition process = this.engine.getRepositoryService().createProcessDefinitionQuery().processDefinitionKey("Process_0amaa0p").latestVersion().singleResult();
        runtimeService.startProcessInstanceById(process.getId(),variables);
    }


    @GetMapping("listWaiting")
    @ResponseBody
    public List<Map> listWaiting(@RequestParam String prtyCode, @RequestParam Long workstationId){
        Integer status = 0;
        return ticketMapper.selectWaiting(prtyCode,status,workstationId);
    }


    @GetMapping("updateStatus")
    @ResponseBody
    public void updateStatus(@RequestParam Integer id, @RequestParam Integer status){
        ticketMapper.updateStatus(id, status);
    }

    @GetMapping("listPassed")
    public List<Map> listPassed(String prtyCode,Long workstationId){
        Integer status = 2;
        return ticketMapper.selectWaiting(prtyCode, status, workstationId);
    }

    @PostMapping("complete")
    @ResponseBody
    public String complete(@RequestBody CompleteParams completeParams){
        TicketTaskDO ticketTaskDO = ticketTaskMapper.selectById(completeParams.getId());
        this.engine.getTaskService().claim(ticketTaskDO.getTaskId(), "doctorw");
        // 经过一系列的业务处理后，将下个流程分配给某几个工作台（groupIds）
        Map<String,Object> variables = new HashMap<>();
        variables.put("workstationIds", completeParams.getWorkstationIds());

        // 转换成group
        List<WorkstationGroupDO> groups = ticketTaskMapper.selectGroups(completeParams.getWorkstationIds());
        List<String> groupIds = groups.stream().map(WorkstationGroupDO::getGroupId).collect(Collectors.toList());
        variables.put("groups", StringUtils.join(groupIds, ","));
        variables.put("pass", false);
//        variables.put("userId", "doctorw");
        // 转换成userId
        // 监听器不生效
        this.engine.getTaskService().complete(ticketTaskDO.getTaskId(), variables);
        // 监听器生效
        return "success";
    }

    @GetMapping("listCompleted")
    public void listCompleted(){

    }
}
